import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class GenrateXSPF {
	private List<String> urls;
	public GenrateXSPF(List<String> urls) {
		if(urls == null || urls.size() <= 0){
			throw new IllegalArgumentException("No URLs to genarate XSPF file");
		}
		this.urls = urls;
	}
	
	public void writeXSPF2File(File file) throws Throwable{
		Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation().createDocument("http://xspf.org/ns/0/", "playlist", null);
		Element root = document.getDocumentElement();
		root.setAttribute("xmlns:vlc", "http://www.videolan.org/vlc/playlist/ns/0/");
		root.setAttribute("version", "1");
		
		Node title = document.createElement("title");
		title.appendChild(document.createTextNode("PlaylistSreeRama"));
		root.appendChild(title);
		
		Element trackList = document.createElement("trackList");
		root.appendChild(trackList);
		
		for(String url : urls){
			Element track = document.createElement("track");
			trackList.appendChild(track);
			Element location = document.createElement("location");
			track.appendChild(location);
			location.appendChild(document.createTextNode(url));
			int lastIndexOfSlash = url.lastIndexOf('/');
			if(lastIndexOfSlash != -1){
				Element trackTitle = document.createElement("title");
				trackTitle.appendChild(document.createTextNode(url.substring(lastIndexOfSlash + 1)));
				track.appendChild(trackTitle);
			}
			if(url != null && url.toLowerCase().startsWith("http")){
				Element extension = document.createElement("extension");
				extension.setAttribute("application", "http://www.videolan.org/vlc/playlist/0");
				Element vlcOptionHTTPCacheing = document.createElementNS("http://www.videolan.org/vlc/playlist/ns/0/", "vlc:option");
				vlcOptionHTTPCacheing.appendChild(document.createTextNode("http-caching=2000"));
				extension.appendChild(vlcOptionHTTPCacheing);
				track.appendChild(extension);
			}
		}
		
		if(!file.getName().toLowerCase().endsWith(".xspf")){
			file = new File(file.getParent(), file.getName() + ".xspf");
		}
		Transformer transformer = TransformerFactory.newInstance().newTransformer();
		transformer.setOutputProperty(OutputKeys.INDENT,"yes");
		transformer.transform(new DOMSource(document), new StreamResult(new OutputStreamWriter(new FileOutputStream(file), "UTF-8")));
	}
}
